function verifyPast(type, updatedAt) {
  // 1=月卡 2=季卡 3=半年卡 4=年卡 5=过期
  const now = Math.round(new Date().getTime() / 1000);
  const end = Math.round(new Date(updatedAt).getTime() / 1000);
  switch (type) {
    case 1:
      if (now - end > 30 * 24 * 60 * 60) {
        return false;
      }
      break;
    case 2:
      if (now - end > 90 * 24 * 60 * 60) {
        return false;
      }
      break;
    case 3:
      if (now - end > 180 * 24 * 60 * 60) {
        return false;
      }
      break;
    case 4:
      if (now - end > 365 * 24 * 60 * 60) {
        return false;
      }
      break;
    case 5:
      return false;
  }

  return true;
}

function genVersion(version) {
  let v = String(parseInt(version.replaceAll(".", "")) + 1);
  var str = "";
  for (var i = 0; i < v.length; i++) {
    str += v[i] + ".";
  }
  return str.substring(0, str.length - 1);
}

function guideRandom() {
  let string = "xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
  let gid = "";
  for (let z of string) {
    let t = 16 * Math.random();
    if (z === "x" || z === "y") {
      let s =
        z === "x"
          ? parseInt(t).toString(16)
          : ((3 & parseInt(t)) | 8).toString(16);
      gid += s;
    } else {
      gid += z;
    }
  }
  return gid.toUpperCase();
}

function getEval(str) {
  try {
    const regex = /\{.*\}/;
    const match = str.match(regex);
    if (match) {
      const obj = JSON.parse(match[0]);
      obj.channel_v = JSON.parse(obj.channel_v);
      return obj;
    }
  } catch (err) {
    return {};
  }
}

function getLidToken(txt) {
  try {
    const target = "aiTabFrameBaseData";

    const index = txt.indexOf("aiTabFrameBaseData") + target.length + 2;

    const str = txt.substring(index);

    const lastIndex = str.indexOf("},");

    const result = str.substring(0, lastIndex + 1) + "}";

    return JSON.parse(result);
  } catch (error) {
    return {};
  }
}

function getConVerSationParams({ chat_token, inputT, query, rank, setype }) {
  return {
    message: {
      inputMethod: "chat_search",
      isRebuild: false,
      content: {
        query: "",
        agentInfo: {
          agent_id: [""],
          params: '{"agt_rk":2,"agt_sess_cnt":5}',
        },
        qtype: 0,
        aitab_ct: "",
        extData: {
          enter_type: "chat_url",
        },
      },
      searchInfo: {
        srcid: "",
        order: "",
        tplname: "",
        re_rank: String(rank),
        ori_lid: "",
        sa: "re_dl_prob_60259",
        chatParams: {
          setype: "csaitab",
          chat_samples: "",
          chat_token: chat_token,
          scene: "",
        },
        blockCmpt: [],
        applid: "",
        a_lid: "",
        enter_type: "chat_url",
      },
      source: "pc_csaitab",
      query: [
        {
          type: "TEXT",
          data: {
            text: {
              query: query,
              text_type: "",
            },
          },
        },
      ],
      anti_ext: {
        inputT: inputT,
        ck1: 141,
        ck9: 416,
        ck10: 582,
      },
    },
    sa: "re_dl_prob_60259",
    rank: rank,
  };
}

function getConVerSationParams2({ chat_token, inputT, query, rank, setype }) {
  return {
    message: {
      inputMethod: "chat_search",
      isRebuild: false,
      content: {
        query: "",
        agentInfo: {
          agent_id: [""],
          params: '{"agt_rk":2,"agt_sess_cnt":1}',
        },
        qtype: 0,
        aitab_ct: "",
        extData: {
          enter_type: "chat_url",
        },
      },
      searchInfo: {
        srcid: "",
        order: "",
        tplname: "",
        re_rank: String(rank),
        ori_lid: "",
        sa: "bkb",
        chatParams: {
          setype: "csaitab",
          chat_samples: "WISE_NEW_CSAITAB",
          chat_token: chat_token,
          scene: "",
        },
        blockCmpt: [],
        usedModel: {
          modelName: "smartMode",
          modelFunction: {
            internetSearch: "0",
          },
        },
        landingPageSwitch: "",
        landingPage: "aitab",
        applid: "",
        a_lid: "",
        enter_type: "chat_url",
        showMindMap: false,
      },
      from: "",
      source: "pc_csaitab",
      query: [
        {
          type: "TEXT",
          data: {
            text: {
              query: query,
              text_type: "",
            },
          },
        },
      ],
      anti_ext: {
        inputT: inputT,
        ck1: 159,
        ck9: 972,
        ck10: 876,
      },
    },
    setype: setype,
    rank: rank,
  };
}

function handleEvent(eventString) {
  const dataLine = eventString
    .split("\n")
    .find((line) => line.startsWith("data:"));
  if (dataLine) {
    return dataLine.replace("data:", "");
  }
}

function sleep(time = 1000) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function getTk(e = "", token = "", lid = "") {
  // const { token, lid } = baiduStore.baiduInfo;
  // const token = "fa1d2d00";
  // const lid = "9870828629916461580";
  return (
    btoa(token + "|" + encodeURIComponent(e) + "|" + Date.now() + "|" + lid) +
    "-" +
    lid
  );
}

function getKuaiDrawConfig({
  aspect_ratio = "4:3",
  imageCount = 4,
  prompt = "",
} = {}) {
  return {
    type: "mmu_txt2img_aiweb",
    inputs: [],
    arguments: [
      {
        name: "prompt",
        value: prompt,
      },
      {
        name: "aspect_ratio",
        value: aspect_ratio,
      },
      {
        name: "imageCount",
        value: imageCount,
      },
      {
        name: "kolors_version",
        value: "1.5",
      },
      {
        name: "style",
        value: "默认",
      },
      {
        name: "biz",
        value: "klingai",
      },
    ],
  };
}

function getIp(ctx) {
  const forwardedFor = ctx.headers["x-forwarded-for"];

  return forwardedFor ? forwardedFor.split(",")[0] : ctx.ip || ctx.request.ip;
}

function generateRandomIP() {
  // 生成后两个八位组（0-255）
  const octet3 = Math.floor(Math.random() * 256); // 第三段：0~255
  const octet4 = Math.floor(Math.random() * 256); // 第四段：0~255
  // 组合成标准IPv4地址
  return `192.168.${octet3}.${octet4}`;
}

function regexBaidu(str) {
  const userRegex =
    /"user":\s*{\s*"username":\s*"([^"]*)",\s*"weakpass":\s*"([^"]*)",\s*"userId":\s*"([^"]*)",\s*"livinguname":\s*"([^"]*)",\s*"portraitUrl":\s*"([^"]*)",\s*"portraitSign":\s*"([^"]*)",\s*"displayName":\s*"([^"]*)"\s*}/;
  const match = str.match(userRegex);
  if (match) {
    const username = match[1];
    const weakpass = match[2];
    const userId = match[3];
    const livinguname = match[4];
    const portraitUrl = match[5];
    const portraitSign = match[6];
    const displayName = match[7];

    return {
      username,
      weakpass,
      userId,
      livinguname,
      portraitUrl,
      portraitSign,
      displayName,
    };
  } else {
    return null;
  }
}

module.exports = {
  verifyPast,
  genVersion,
  guideRandom,
  getEval,
  getLidToken,
  getConVerSationParams,
  getConVerSationParams2,
  handleEvent,
  sleep,
  getKuaiDrawConfig,
  getTk,
  getIp,
  generateRandomIP,
  regexBaidu,
};
